#include "stdafx.h"
#include "Frame.hxx"
#include "framepool.hxx"

FramePool::FramePool()
{
    _pageCount = 50;
    _pageSize = RAW_FRAME_WIDTH * RAW_FRAME_HEIGHT * 3 / 2;
    _pool = 0;

	::InitializeCriticalSection( &_keyCs );
}

FramePool::~FramePool()
{
	if( _pool ) 
		free( _pool );
	_pool = 0;

	::DeleteCriticalSection( &_keyCs );
}


void FramePool::initialize()
{
    _freeKeys.empty();
    _poolKeys.empty();

    if( _pool ) free( _pool );
    _pool = (char*)malloc( _pageCount * _pageSize );

    for( int i = 0; i < _pageCount; i ++ )
    {
        _freeKeys.push( i );
    }
}

bool FramePool::pushFrame(const char *buf)
{
    if( _freeKeys.size() > 0 )
    {
        //_keyMutex.lock();
		::EnterCriticalSection( & _keyCs );
        
		int key = _freeKeys.front();
        _freeKeys.pop();
        _poolKeys.push( key );
		memcpy( _pool + _pageSize * key, buf, _pageSize );
        
		//_keyMutex.unlock();
		::LeaveCriticalSection( & _keyCs );
        
        return true;
    }
    else
    {
		printf("Lost a frame...\n");
        return false;
    }
}

bool FramePool::popFrame(char *buf)
{
	int sz = _poolKeys.size();
    if( sz > 0 )
    {
        //_keyMutex.lock();
		::EnterCriticalSection( &_keyCs );
        int key = _poolKeys.front();
        _poolKeys.pop();
        _freeKeys.push( key );
        //_keyMutex.unlock();
		::LeaveCriticalSection( &_keyCs );

        memcpy( buf, _pool + _pageSize * key, _pageSize );
        return true;
    }
    else
    {
        return false;
    }
}
